package aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;

public class Server {

    public Server(int port) throws IOException {

        final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));
        listener.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {

            @Override
            public void completed(AsynchronousSocketChannel result, Void attachment) {

                listener.accept(null, this);
                handle(result);
            }

            @Override
            public void failed(Throwable exc, Void attachment) {

            }
        });
    }

    public void handle(AsynchronousSocketChannel result) {

        ByteBuffer buffer = ByteBuffer.allocate(32);
        try {
            result.read(buffer).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        buffer.flip();
        System.out.println(buffer.get());
    }

    public static void main(String[] args) throws IOException, InterruptedException {

        Server server = new Server(8888);
        Thread.sleep(1000000);
    }
}
